from datetime import datetime

from aiogram import types
from aiogram_dialog import DialogManager
from fluentogram import TranslatorRunner

from src.database.services import CalendarService, UserService


async def proccess_new_time(
    message: types.Message,
    _,
    manager: DialogManager,
    new_time: str,
):
    locale: TranslatorRunner = manager.middleware_data.get("locale")
    calendar_service: CalendarService = manager.middleware_data.get("calendar_service")
    time_to_change: str = manager.dialog_data.get("time_to_change")
    user_calendar_id: int = manager.dialog_data.get("user_calendar_id")

    try:
        new_time = datetime.strptime(new_time, "%H:%M").time()
    except ValueError:
        await message.answer(locale.get("incorrect-time-format"))
        return
    if time_to_change == "check_task_time":
        await calendar_service.update_user_check_tasks_time(user_calendar_id, new_time)
    else:
        await calendar_service.update_user_get_tasks_time(user_calendar_id, new_time)

    await message.answer(locale.get("time-changed"))

    await manager.done()
